
//不写泛型了，就直接写朴素的代码，假定存储的元素是int
//基于数组来实现队列
/*实现阻塞队列分三步 ：
1.先实现一个普通队列  2.加上线程安全  3.加上阻塞功能*/
class MyBlockingQueue {
    volatile private int[] items = new int[1000];
    //约定 [head， tail) 为队列的有效元素
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;

    //入队列
    synchronized public void put(int value) throws InterruptedException {
        while (size == items.length) {
            /*此处while比if好，因为别处如果有一个暗中的interrupt唤醒了wait，
              但是此时还不满足条件，就会出bug*/
            //队列满了，无法放入元素
            //return;
            this.wait();
        }
        //把新的元素放入到队列中
        items[tail] = value;
        tail++;
        //万一tail 达到末尾，就需要让tail从队头重新开始
        while (tail == items.length - 1) {
            tail = 0;
        }
        size++;
        this.notify();
    }
    //出队列
    synchronized public Integer take() throws InterruptedException {
        if (size == 0) {
            //return null;
            this.wait();
        }
        int value = items[head];
        head++;
        if (head == items.length) head = 0;
        size--;
        this.notify();
        return value;
    }
}

public class ThreadDemo22 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        //消费者
        Thread t1 = new Thread(() -> {
            while (true) {
                try {
                    int value = queue.take();
                    System.out.println("消费：" + value);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        //生产者
        Thread t2 = new Thread(() -> {
            int value = 0;
            while (true) {
               try {
                   System.out.println("生产：" + value);
                   queue.put(value);
                   //Thread.sleep(1000);
                   value++;
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
            }
        });

        t1.start();
        t2.start();
    }
}
